/**
 * 返回页面url, 指定键的参数值
 */

import { useSearchParams, URLSearchParamsInit } from "react-router-dom";
import { useMemo, useState } from "react";
import { cleanObject, subset } from "utils";

// export const useUrlQueryParam = <K extends string>(keys: K[]) => {
//   const [searchParams] = useSearchParams();
//   const setSearchParams = useSetUrlSearchParam();
//   const [stateKeys] = useState(keys);
//   return [
//     useMemo(
//       () =>
//         keys.reduce((prev, key) => {
//           return { ...prev, [key]: searchParams.get(key) || "" };
//         }, {} as { [key in K]: string }),
//       [searchParams, stateKeys]
//     ),
//     (params: Partial<{ [key in K]: unknown }>) => {
//       // const o = cleanObject({
//       //   ...Object.fromEntries(searchParams),
//       //   ...params,
//       // }) as URLSearchParamsInit;
//       return setSearchParams(params);
//     },
//   ] as const;
// };

export const useUrlQueryParam = <K extends string>(keys: K[]) => {
  const [searchParams] = useSearchParams();
  const setSearchParams = useSetUrlSearchParam();
  const [stateKeys] = useState(keys);
  return [
    useMemo(
      () =>
        subset(Object.fromEntries(searchParams), stateKeys) as {
          [key in K]: string;
        },
      [searchParams, stateKeys]
    ),
    (params: Partial<{ [key in K]: unknown }>) => {
      return setSearchParams(params);
      // iterator
      // iterator: https://codesandbox.io/s/upbeat-wood-bum3j?file=/src/index.js
    },
  ] as const;
};

export const useSetUrlSearchParam = () => {
  const [searchParams, setSearchParam] = useSearchParams();
  return (params: { [key in string]: unknown }) => {
    const o = cleanObject({
      ...Object.fromEntries(searchParams),
      ...params,
    }) as URLSearchParamsInit;
    return setSearchParam(o);
  };
};

const a = ["jack", 12, { gender: "male" }] as const;
